﻿using Fast.DynamicApiController.Conventions;
using Fast.Filters;
using Fast.Middlewares;
using Fast.ServiceCollection;
using Fast.UnifyResult.Providers;
using Fast.Web.Core.Provider;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Fast.Web.Core
{
    public class Startup
    {
        public IConfiguration _configuration { get; }

        // 构造函数注入 IConfiguration
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        // 注册服务
        public void ConfigureServices(IServiceCollection services)
        {

            // 注册 UnifyResultFilter 作为作用域服务
            services.AddScoped<UnifyResultFilter>(); // 注册过滤器
            services.AddSingleton<IUnifyResultProvider, RESTfulResultProvider>(); // 注册 RESTfulResultProvider

            // 注册自定义的应用模型约定
            services.AddControllers(options =>
            {
                options.Conventions.Add(new DynamicApiControllerApplicationModelConvention());
                options.Filters.AddService<UnifyResultFilter>();  // 通过依赖注入添加过滤器
            }).AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            });

            // 注册 Swagger 服务
            services.AddEndpointsApiExplorer(); // 必须有
            services.AddSwaggerGen(options =>
            {
                //忽略没有配置 HttpMethod 特性的接口
                //options.DocInclusionPredicate((_, api) =>
                //    !string.IsNullOrWhiteSpace(api.HttpMethod));

                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "My API",
                    Version = "v1",
                    Description = "这是我的自定义 API 文档"
                });

                // 生成接口xml文件,swagger使用
                // 获取所有已加载程序集
                var assemblies = AppDomain.CurrentDomain.GetAssemblies();

                // 遍历名称包含 "Application" 的程序集，拿路径拼 XML 路径
                foreach (var assembly in assemblies)
                {
                    if (assembly.GetName().Name?.Contains("Application") == true)
                    {
                        var assemblyPath = Path.GetDirectoryName(assembly.Location);
                        if (assemblyPath != null)
                        {
                            var xmlPath = Path.Combine(assemblyPath, $"{assembly.GetName().Name}.xml");
                            if (File.Exists(xmlPath))
                            {
                                // 这里可以注册 IncludeXmlComments 或其他逻辑
                                options.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
                            }
                        }
                    }
                }
            });

            // 自动扫描并注册服务
            services.AddAutoInjectedServices();

            // 读取配置
            var allowedOrigins = _configuration.GetSection("Cors:AllowedOrigins").Get<string[]>();
            //配置跨域
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    // 允许指定的前端地址
                    builder.WithOrigins(allowedOrigins ?? Array.Empty<string>()) 
                           .AllowAnyHeader()
                           .AllowAnyMethod();
                });
            });
        }

        // 配置HTTP请求管道
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();

                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                    c.RoutePrefix = ""; // Swagger UI 将显示在 /docs 下
                });

            }

            app.UseMiddleware<GlobalExceptionMiddleware>();  // 注册全局异常处理中间件
            app.UseCors();//启用跨域
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers(); // 默认路由配置，但不使用特性路由限制
            });
        }
    }

}
